﻿using Nasty.Core.LoadParams;
using Nasty.Core.Repository;
using Nasty.Core.SuperExtension;
using Nasty.QuartzModule.Areas.QuartzTask.Model;
using Nasty.QuartzModule.Areas.QuartzTask.Params;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Nasty.QuartzModule.QuartzTask
{
    public interface IQuartzTaskRepository : IRepository<QuartzTask>
    {
        public QuartzTask GetQuartzTask(string id);

        public ResultData<QuartzTask> SaveQuartzTask(QuartzTaskModel model);

        public ResultData<string> DeleteQuartzTasks(List<string> ids);

        public PageData<QuartzTask> GetQuartzTaskPage(GetQuartzTaskPageParams @params);

        public List<QuartzTask> GetQuartzTasks(GetQuartzTasksParams @params);

        public ResultData<string> SetQuartzTaskEnabled(SetQuartzTaskEnabledParams @params);

        public PageData<QuartzTaskLog> GetQuartzTaskLogPage(GetQuartzTaskLogPageParams @params);
    }

    public class QuartzTaskRepository : SqlRepository<QuartzTask>, IQuartzTaskRepository
    {
        public QuartzDynamicService QuartzDynamicService { get; set; }

        public QuartzTaskRepository(SqlSugarClient db) : base(db)
        {
            //db.CodeFirst.InitTables(typeof(QuartzTask));
            //db.CodeFirst.InitTables(typeof(QuartzTaskLog));
        }

        public ResultData<string> DeleteQuartzTasks(List<string> ids)
        {
            var result = new ResultData<string>();
            try
            {
                Db.Delete<QuartzTask>(ids);
                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }

        public QuartzTask GetQuartzTask(string id)
        {
            return this.Db.Queryable<QuartzTask>().IncludesAllFirstLayer().InSingle(id);
        }

        public ResultData<QuartzTask> SaveQuartzTask(QuartzTaskModel model)
        {
            var result = new ResultData<QuartzTask>();
            try
            {
                var data = Db.Save<QuartzTask>(model);
                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }

        public PageData<QuartzTask> GetQuartzTaskPage(GetQuartzTaskPageParams @params)
        {
            int totalPage = 0;
            int total = 0;
            var pageData = new PageData<QuartzTask>();

            var _SQLExpress = Db.Queryable<QuartzTask>().IncludesAllFirstLayer();

            if (!string.IsNullOrEmpty(@params.Name)) _SQLExpress.Where((t) => t.Name.Contains(@params.Name));
            if (!string.IsNullOrEmpty(@params.Group)) _SQLExpress.Where((t) => t.Group.Contains(@params.Group));
            _SQLExpress = _SQLExpress.OrderBy((t) => t.CreateTime, OrderByType.Desc);

            var data = _SQLExpress.ToPageList(@params.Current, @params.PageSize, ref total, ref totalPage);

            pageData.Total = total;
            pageData.TotalPage = totalPage;
            pageData.Data = data;

            pageData.Current = @params.Current;
            pageData.PageSize = @params.PageSize;
            return pageData;
        }

        public List<QuartzTask> GetQuartzTasks(GetQuartzTasksParams @params)
        {
            var _SQLExpress = Db.Queryable<QuartzTask>();
            if (!string.IsNullOrEmpty(@params.Group)) _SQLExpress.Where((t) => t.Group.Contains(@params.Group));
            return _SQLExpress.ToList();
        }

        public ResultData<string> SetQuartzTaskEnabled(SetQuartzTaskEnabledParams @params)
        {
            var result = new ResultData<string>();
            try
            {
                Db.BeginTran();
                var data = Db.Queryable<QuartzTask>().InSingle(@params.Id);
                data.IsEnabled = @params.IsEnabled;

                Db.Update(data);

                if (@params.IsEnabled)
                {
                    var jobType = Type.GetType(data.Class);
                    if(jobType == null) throw new Exception("加入Job失败,请检查类名");

                    var jobResult = QuartzDynamicService.AddJobAsync(data, jobType).Result;
                    if (!jobResult) throw new Exception("加入Job失败,请检查类名,表达式");
                }
                else
                {
                    var jobResult = QuartzDynamicService.DeleteJobAsync(data);
                }

                Db.CommitTran();
                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                Db.RollbackTran();
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }

        public PageData<QuartzTaskLog> GetQuartzTaskLogPage(GetQuartzTaskLogPageParams @params)
        {
            int totalPage = 0;
            int total = 0;
            var pageData = new PageData<QuartzTaskLog>();

            var _SQLExpress = Db.Queryable<QuartzTaskLog>().IncludesAllFirstLayer();

            if (!string.IsNullOrEmpty(@params.TaskId)) _SQLExpress.Where((t) => t.TaskId.Contains(@params.TaskId));
            if (!string.IsNullOrEmpty(@params.Result)) _SQLExpress.Where((t) => t.Result.Contains(@params.Result));

            _SQLExpress = _SQLExpress.OrderBy((t) => t.CreateTime, OrderByType.Desc);
            var data = _SQLExpress.ToPageList(@params.Current, @params.PageSize, ref total, ref totalPage);

            pageData.Total = total;
            pageData.TotalPage = totalPage;
            pageData.Data = data;

            pageData.Current = @params.Current;
            pageData.PageSize = @params.PageSize;
            return pageData;
        }
    }
}
